<?php
/**
 * Auth: (C) 2013 ljwnet@163.com
 * $Action: ci形式mvc处理
 * @update	2017-06-28
 */

/**
 * 加载
 * @return [type] [是否已成功载过]
 */
function load($file_name)
{
	global $loadedFile;
	if(!in_array($file_name,$loadedFile)){
		if(is_file($file_name)){
			include $file_name;
			$loadedFile[] = $file_name;
			return true;
		}else{
			return false;
		}
	}else{
		return true;
	}
}

/**
 * 引入控制器
 * @param  string	$ctrl_name		控制名
 * @param  string	$app_dir 		控制所属子项目名
 * @return object
 */
function c($ctrl_name,$app_dir = 'api')
{
	$ctrl_file = APP_ROOT.$app_dir.DS.'ctrl'.DS.$ctrl_name.'.php';
	if(load($ctrl_file)){
		if(class_exists($ctrl_name)){

			$op = new $ctrl_name;
			return $op;
		}else{
			$op = "$ctrl_name Class not found";
		}
	}else{
		$op = "$ctrl_file not found";
	}
	exit($op);
}

/**
 * 引入模型
 * @param  string $model_name 模型名
 * @param  string $app_dir 		控制所属子项目名
 * @return object
 */
function m($model_name,$app_dir = 'api')
{
	$model_file = APP_ROOT.$app_dir.DS.'model'.DS.$model_name.'.php';
	if(load($model_file)){
		if(class_exists($model_name)){
			$str = $model_name.'M';
			global $$str;
			if(!is_object($$str))
				$$str = new $model_name;
			// p($$str);
			return $$str;
		}else{
			$op = "$model_name Class not found";
		}
	}else{
		$op = "$model_file not found";
	}
	exit($op);
}


function run($app_dir = 'api',$parentClass = '')
{
	$router = get_param('ac');
	$op = '';
	if($router){
		$rt_arr = explode('/',$router);
		if(!empty($rt_arr[0]) && !empty($rt_arr[1])){
			if($parentClass){//引入基础
				$parentClass_file = APP_ROOT.$app_dir.DS.'ctrl'.DS.$parentClass.'.php';
				if(load($parentClass_file)){
					if(!class_exists($parentClass)){
						$op = "$parentClass parentClass not found";
						die($op);
					}
				}else{
					$op = "$parentClass_file not found";
					die($op);
				}
			}
			$ctrl = $rt_arr[0];	//控制器名	
			$api = $rt_arr[1]; //具体api_function

			$ctrl_class = c($ctrl,$app_dir); //接口实例
			if(is_object($ctrl_class)){
				if(method_exists($ctrl_class,"$api")){
					$op = $ctrl_class->$api();
					if(is_array($op))
						op($op);
				}else{
					$op = "$ctrl->$api function not found";
				}
			}else{
				$op = $ctrl_class;
			}
		}else{
			$op = 'route ?/?';
		}
	}else{
		$op = 'route ???';
	}
	die($op);
}
